<template>
  <view class="alt-picture" :class="{ 'alt-background': showEmptyIcon && !transparent }">
    <image v-show="!showEmptyIcon" class="picture" :src="src" :mode="mode" @load="onLoad" @error="onError" />
    <view v-if="showEmptyIcon" class="empty-icon" />
  </view>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    src?: string | undefined
    mode?: 'scaleToFill' | 'aspectFit' | 'aspectFill' | 'widthFix' | 'heightFix'
    transparent?: boolean
  }>(),
  {
    mode: 'aspectFit',
  }
)

const imageLoaded = ref(false)
const imageLoadError = ref(false)
const showEmptyIcon = computed(() => !imageLoaded.value || imageLoadError.value)
watch(
  () => props.src,
  (newSrc, oldSrc) => {
    if (newSrc === oldSrc) return
    imageLoaded.value = false
    imageLoadError.value = false
  }
)

function onLoad() {
  imageLoaded.value = true
}
function onError() {
  imageLoadError.value = true
}
</script>

<style lang="less">
.alt-picture {
  width: 100%;
  height: 100%;
  position: relative;
  &.alt-background {
    background-color: #f4f4f6;
  }
  .picture,
  .empty-icon {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .empty-icon {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20width%3D%22100%22%20height%3D%22100%22%20viewBox%3D%220%200%20100%20100%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%3Cpath%20d%3D%22M75.7756%2065.3573C78.4595%2060.8629%2080%2055.622%2080%2050C80%2033.4357%2066.5643%2020%2050%2020C33.4357%2020%2020%2033.4357%2020%2050C20%2066.5643%2033.4357%2080%2050%2080C55.6061%2080%2060.8629%2078.4595%2065.3574%2075.7755L76.8237%2078.6183C77.9037%2078.8883%2078.8724%2077.9195%2078.6025%2076.8396L75.7756%2065.3573ZM62.2128%2060.847C62.2128%2061.657%2061.5458%2062.324%2060.7359%2062.324H40.1535C39.3436%2062.324%2038.6765%2061.657%2038.6765%2060.847V42.7422C38.6765%2042.3134%2038.8671%2041.9005%2039.1847%2041.6305L49.4759%2032.7051C50.0318%2032.2287%2050.8576%2032.2287%2051.4134%2032.7051L61.7046%2041.6305C62.0222%2041.9164%2062.2128%2042.3134%2062.2128%2042.7422V60.847Z%22%20fill%3D%22%23E9E9ED%22%2F%3E%0A%3C%2Fsvg%3E%0A');
  }
}
</style>
